package com.szlanyou.thirdsdk.retrofit.util;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author 陈章
 * create at 2020/12/23 10:47
 * desc:
 */
public class GsonUtil {
    public static final Gson gson = new Gson();
    /** 将指定的json数据转成 {@link HashMap}<String, Object>对象 */
    public  static HashMap< String, Object > fromJson(String jsonStr) {
        try {
            if (jsonStr.startsWith("[") && jsonStr.endsWith("]")) {
                jsonStr = "{\"fakelist\":" + jsonStr + "}";
            }

            JSONObject json = new JSONObject(jsonStr);
            return fromJson(json);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return new HashMap< String, Object >();
    }

    private static  HashMap< String, Object > fromJson(JSONObject json) throws JSONException {
        HashMap< String, Object > map = new HashMap< String, Object >();
        @SuppressWarnings("unchecked")
        Iterator< String > iKey = json.keys();
        while (iKey.hasNext()) {
            String key = iKey.next();
            Object value = json.opt(key);
            if (JSONObject.NULL.equals(value)) {
                value = null;
            }
            if (value != null) {
                if (value instanceof JSONObject) {
                    value = fromJson((JSONObject) value);
                } else if (value instanceof JSONArray) {
                    value = fromJson((JSONArray) value);
                }
                map.put(key, value);
            }
        }
        return map;
    }

    private static ArrayList< Object > fromJson(JSONArray array) throws JSONException {
        ArrayList< Object > list = new ArrayList< Object >();
        for (int i = 0, size = array.length(); i < size; i++) {
            Object value = array.opt(i);
            if (value instanceof JSONObject) {
                value = fromJson((JSONObject) value);
            } else if (value instanceof JSONArray) {
                value = fromJson((JSONArray) value);
            }
            list.add(value);
        }
        return list;
    }

}
